class UsersController < ApplicationController
  # POST /users
  # POST /users.xml
  # params structure  
  def create
    @user = User.new(params[:user])    
    @subject_ids = params[:subjects] || []
    @grade_ids = params[:grades] || []

    respond_to do |format|
      if @user.save
        query = []
        @grade_ids.each do |grade_id|
          query << "INSERT INTO grades_users(grade_id,user_id) VALUES(#{grade_id.to_i},#{@user.id})"
        end

        @subject_ids.each do |subject_id|
          query << "INSERT INTO subjects_users(subject_id,user_id) VALUES(#{subject_id.to_i},#{@user.id})"
        end  
        User.find_by_sql(query.join(';'))
        flash[:notice] = 'User was successfully created.'
        format.html { redirect_to(@user) }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  def add_coin
    user = User.find(params[:user_id])
    code = params[:code]

    point = 0
    if code == '1234567890'
      point = 100000
    elsif code == '1234567891'  
      point = 50000
    elsif code == '1234567892'
      point = 150000
    elsif code == '1234567893'  
      point = 200000
    end
    user.point = user.point || 0
    user.point += point
    user.save
    render :json => {:point => user.point}
  end

  def remove_coin
    user = User.find(params[:user_id])
    point = params[:point].to_i
    user.point -= point
    user.save
    render :json => {:point => user.point}    
  end
end
